import '../main.js'

export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function() {
  }
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export function scorePassword(pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
    letters[pass[i]] = (letters[pass[i]] || 0) + 1
    score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(pass),
    lower: /[a-z]/.test(pass),
    upper: /[A-Z]/.test(pass),
    nonWords: /\W/.test(pass)
  }

  let variationCount = 0
  for (var check in variations) {
    variationCount += (variations[check] === true) ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

/*
 * 封装公共金额转化大小写文件
 * @author   王天瑜
 * @date     2019-06-14
 */
export function moneyCN(n) {
  if (!n) {
    n = 0
  }
  if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
    return ''
  }
  if (parseFloat(n) === 0) {
    return '零'
  }

  var unit = '仟佰拾亿仟佰拾万仟佰拾圆角分'
  var str = ''
  n += '00'
  var p = n.indexOf('.')
  if (p >= 0) {
    n = n.substring(0, p) + n.substr(p + 1, 2)
  }
  unit = unit.substr(unit.length - n.length)

  for (var i = 0; i < n.length; i++) {
    str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i)
  }
  return str.replace(/零(仟|佰|拾|角)/g, '零')
    .replace(/(零)+/g, '零')
    .replace(/零(万|亿|圆)/g, '$1')
    .replace(/(亿)万|壹(拾)/g, '$1$2')
    .replace(/^圆零?|零分/g, '')
    .replace(/圆$/g, '圆整')
}

export function addUrlParm(url, key, value) {
  var returnUrl = ''
  if (url.indexOf('?') === -1) {
    returnUrl += url + '?' + key + '=' + value
  } else {
    if (url.indexOf('?' + key + '=') === -1 && url.indexOf('&' + key + '=') === -1) {
      returnUrl += url + '&' + key + '=' + value
    } else {
      var isDone = false
      var startIndex = 0
      var endIndex = url.length - 1
      var parm = '?' + key + '='
      for (var i = 0; i < url.length; i++) {
        if (url.substr(i, parm.length) === parm) {
          startIndex = i + parm.length
          for (var j = startIndex; j < url.length; j++) {
            if (url[j] === '&') {
              endIndex = j
              break
            } else if (j === url.length - 1) {
              endIndex = url.length
            }
          }
          isDone = true
          break
        }
      }
      if (!isDone) {
        parm = '&' + key + '='
        for (var i1 = 0; i1 < url.length; i1++) {
          if (url.substr(i1, parm.length) === parm) {
            startIndex = i1 + parm.length
            for (var j1 = startIndex; j1 < url.length; j1++) {
              if (url[j1] === '&') {
                endIndex = j1
                break
              } else if (j1 === url.length - 1) {
                endIndex = url.length
              }
            }
            break
          }
        }
      }
      var parmKeyValue = parm + url.substring(startIndex, endIndex)
      returnUrl = url.replace(parmKeyValue, parm + value)
    }
  }
  if (!value) {
    returnUrl = returnUrl.replace(key + '=' + value, '')
  }
  return returnUrl
}

export function getTheme() {
  return process.env.VUE_APP_THEME_PAGE
}

/**
 * 判断是否为空
 * @param value 值
 * @returns {boolean}
 */
export function isEmpty(value) {
  return value === '' || value === undefined || value === 'undefined' || value === null || value.length === 0 ||
    JSON.stringify(value) === '{}'
}

/**
 * 正则表达式判断是否为 number
 * @param value 要判断的值
 * @returns {boolean} true: 是number
 */
export function isNumber(value) {
  return /^\d+$/.test(value)
}

/**
 * 判断是否位数字，可以包含小数点
 * @param value 判断的值
 * @returns {boolean} true：为数字，false：不是数字
 */
export function isNumeric(value) {
  return !isNaN(parseFloat(value)) && isFinite(value)
}

/**
 * 正则表达式判断是否为 英文字母
 * @param value 要判断的值
 * @returns {boolean} true: 是number
 */
export function isEnglish(value) {
  return /[A-Za-z]+/.test(value)
}

/**
 * 转为状态名称
 * @param status
 * @param arr
 * @returns {*}
 */
export function getStatusName(status, arr) {
  let statusName = status
  for (const item in arr) {
    if (arr[item].value === status) {
      statusName = arr[item].options[1]
      break
    }
  }
  return statusName
}

/**
 * 根据状态获取 type
 * @param status
 * @returns {string}
 */
export function getTypeByStatus(status) {
  switch (status) {
    case 'AUDIT_SUCCESS':
      return 'success'
    case 'AUDITING':
      return 'warning'
    case 'NORMAL':
      return ''
    default:
      return 'info'
  }
}

/**
 * 图片预览图需要为 list 结构的数据
 * @param list
 * @returns {*[]}
 */
export function getPreviewList(list) {
  const fileUrls = []
  if (isEmpty(list)) {
    return fileUrls
  }
  list.forEach(value => fileUrls.push(value.fileUrl))
  return fileUrls
}

/**
 * 睡眠
 * @param sleepTime
 * @returns {Promise<unknown>}
 */
export function sleep(sleepTime) {
  var start = new Date().getTime()
  while (!isEmpty(sleepTime)) {
    if (new Date().getTime() - start > sleepTime) {
      break
    }
  }
}

/**
 * 获取UUID
 * @returns {string|*}
 */
export function getUuid() {
  if (typeof crypto === 'object') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID()
    }
    if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
      const callback = (c) => {
        const num = Number(c)
        return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16)
      }
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, callback)
    }
  }
  let timestamp = new Date().getTime()
  let perforNow = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    let random = Math.random() * 16
    if (timestamp > 0) {
      random = (timestamp + random) % 16 | 0
      timestamp = Math.floor(timestamp / 16)
    } else {
      random = (perforNow + random) % 16 | 0
      perforNow = Math.floor(perforNow / 16)
    }
    return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
  })
}

/**
 * 判断是否为移动端的宽度
 * @returns {boolean} true：是移动端
 */
export function getMobileWidthFlag() {
  const windowWidth = document.documentElement.clientWidth
  let mobileWidthFlag = true
  if (windowWidth >= 992) {
    mobileWidthFlag = false
  }
  return mobileWidthFlag
}

/**
 * 乘法
 * @param num1 乘数1
 * @param num2 乘数2
 * @returns {number} 结果
 */
export function multiply(num1, num2) {
  return (num1 * num2).toFixed(2)
}

/**
 * 限制只保留两位小数
 * @param val 输入值
 * @returns {number} 结果
 */
export function limitTwoDecimal(val) {
  // 判断是否有小数点
  if (val.indexOf('.') > 0) {
    const length = val.split('.')[1].length
    // 如果小数点后的值大于2位，则需要处理
    if (length > 2) {
      return Number(val).toFixed(2)
    }
  }
  return val
}

/**
 * 限制保留小数
 * @param val 输入值
 * @param fractionDigits 需要保留小数的长度
 * @returns {number} 结果
 */
export function limitDecimal(val, fractionDigits) {
  // 先转为字符串
  val = val + ''
  // 判断是否有小数点
  if (val.indexOf('.') > 0) {
    const length = val.split('.')[1].length
    // 如果小数点后的值大于2位，则需要处理
    if (length > fractionDigits) {
      return Number(val).toFixed(fractionDigits)
    }
  }
  return val
}

